package com.czy.daishusys.ui.personal;

import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.czy.daishusys.R;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseActivity;
import com.czy.daishusys.utils.GetDeviceId;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.czy.daishusys.widget.MyEditText;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author: Raven
 * @date: 2017/11/28 13:44
 * @email: xiexiaomeng_001@163.com
 * @description: 修改用户昵称
 */

public class EditNickNameActivity extends BaseActivity {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarSubtitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.et_nick_name)
    MyEditText etNickName;
    @BindView(R.id.btn_save)
    Button btnSave;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_edit_nick_name;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.nick_name_modify_title);
        String savedNickName = UserHelper.getInstance().getUserInfoModel(this).getNickName();

        if(savedNickName != null) {
            etNickName.setText(savedNickName);
            etNickName.setSelection(savedNickName.length());
        }
        etNickName.addTextChangedListener(new EditChangedListener());
    }

    @Override
    protected void updateViews() {

    }

    @OnClick(R.id.btn_save)
    protected void OnViewClicked(View view){
        switch (view.getId()){
            case R.id.btn_save:
                String newNickName = etNickName.getText().toString();
                if(!TextUtils.isEmpty(newNickName)) {
                    updateNickName(newNickName);
                }
                break;
        }
    }

    private void updateNickName(final String newNickName){
        HttpParams params =  new HttpParams();
        params.put("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.put("nickName", newNickName);
        params.put("pid",UserHelper.getInstance().getDevicePid());
        EasyHttp.post(Constants.UPDATE_ADMIN_INFO)
                .params(params)
                .timeStamp(true)//添加时间戳
                .execute(new SimpleCallBack<String>() {

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(String s) {
                        String data = PhoneUtils.checkResponseFlag(EditNickNameActivity.this,s);
                        if(data!=null){
                            PhoneUtils.ShowToastMessage(EditNickNameActivity.this, "修改成功");
                            UserHelper.getInstance().getUserInfoModel(EditNickNameActivity.this).setNickName(newNickName);
                            Intent intent = new Intent();
                            intent.putExtra("nick_name", newNickName);
                            setResult(AccountSettingsActivity.NICK_NAME, intent);
                            EditNickNameActivity.this.finish();
                        }
                    }
                });
    }

    class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            check();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    private void check() {
        int mTextMaxlenght = 0;
        Editable editable = etNickName.getText();
        String str = editable.toString().trim();
        //得到最初字段的长度大小，用于光标位置的判断
        int selEndIndex = Selection.getSelectionEnd(editable);
        // 取出每个字符进行判断，如果是字母数字和标点符号则为一个字符加1，
        //如果是汉字则为两个字符
        for (int i = 0; i < str.length(); i++) {
            char charAt = str.charAt(i);
            //32-122包含了空格，大小写字母，数字和一些常用的符号，
            //如果在这个范围内则算一个字符，
            //如果不在这个范围比如是汉字的话就是两个字符
            if (charAt >= 32 && charAt <= 122) {
                mTextMaxlenght++;
            } else {
                mTextMaxlenght += 2;
            }
            // 当最大字符大于20时，进行字段的截取，并进行提示字段的大小
            if (mTextMaxlenght > 20) {

                // 截取最大的字段
                String newStr = str.substring(0, i);
                etNickName.setText(newStr);

                // 得到新字段的长度值
                editable = etNickName.getText();
                int newLen = editable.length();
                if (selEndIndex > newLen) {
                    selEndIndex = editable.length();
                }
                // 设置新光标所在的位置
                Selection.setSelection(editable, selEndIndex);
                PhoneUtils.ShowToastMessage(EditNickNameActivity.this, getString(R.string.nick_name_tip));
            }
        }


    }

}
